package com.yuezhi.acl.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.yuezhi.acl.entity.SysRole;
import com.yuezhi.acl.entity.SysUser;
import com.yuezhi.acl.service.IndexService;
import com.yuezhi.acl.service.SysPermissionService;
import com.yuezhi.acl.service.SysRoleService;
import com.yuezhi.acl.service.SysUserService;
import com.yuezhi.exception.YueZhiException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @program: yuezhi-parent
 * @description:
 * @author: Mr.Liao
 * @create: 2020-12-16 14:21
 **/
@Service
public class IndexServiceImpl implements IndexService {

    @Autowired
    private SysUserService userService;

    @Autowired
    private SysRoleService roleService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 根据用户名获取用户登录信息
     *
     * @param username
     * @return
     */
    @Override
    public Map<String, Object> getUserInfo(String username) {
        Map<String, Object> result=new HashMap<>();
        SysUser sysUser = userService.selectByUsername(username);
        if(null == sysUser){
            throw new YueZhiException(202,"用户不存在");
        }
        //根据用户id获取角色
        List<SysRole> sysRoles = roleService.selectRoleByUserId(sysUser.getId());
        List<String> roleNameList = sysRoles.stream().map(item -> item.getRoleName()).collect(Collectors.toList());
        if( roleNameList.size()==0){
            //前端框架必须返回一个角色，否则报错，如果没有角色，返回一个空角色
            roleNameList.add("");
        }
        //根据用户id获取操作权限值
        List<String> permissionValueList = permissionService.selectPermissionValueByUserId(sysUser.getId());
        redisTemplate.opsForValue().set(username,permissionValueList);
        result.put("name",sysUser.getUsername());
        result.put("avatar","https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        result.put("roles",roleNameList);
        result.put("permissionValueList",permissionValueList);
        return result;
    }

    /**
     * 根据用户名获取动态菜单
     * @param username
     * @return
     */
    @Override
    public List<JSONObject> getMenu(String username) {
        SysUser sysUser = userService.selectByUsername(username);
        //根据用户id获取用户菜单权限
        List<JSONObject> jsonObjects = permissionService.selectPermissionByUserId(sysUser.getId());
        return jsonObjects;
    }
}
